package com.artup.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.MaterialDao;
import com.artup.dao.MaterialEditDao;
import com.artup.dao.PictureDao;
import com.artup.pojo.Material;
import com.artup.service.MaterialService;
import com.artup.to.MaterialTo;
import com.artup.util.CommonUtils;
import com.artup.util.cache.RedisUtils;
import com.artup.util.file.FileHelper;
import com.artup.util.file.FolderUtils;
import com.artup.util.file.PropertiesUtils;
import com.artup.util.image.ImageUtil;
import com.artup.util.os.OperationSystemInfo;
import com.artup.util.shell.ChmodShell;
import com.artup.vo.MaterialVo;

import redis.clients.jedis.Jedis;

@Service( value = "materialService" )
public class MaterialServiceImpl implements MaterialService {
	private static final Logger LOGGER = LoggerFactory.getLogger(MaterialServiceImpl.class);
	
	private static int BIG_THUMBNAIL_SHORTEST_SIDE_LENGTH = 740;	// 大缩略图最短边长，默认 740px
	private static int SMALL_THUMBNAIL_SHORTEST_SIDE_LENGTH = 200;	// 小缩略图最短边长，默认 200px
	
	private static Jedis jedis = RedisUtils.getJedis();
	
	@Autowired
	private PictureDao pictureDao;
	
	@Autowired
	private MaterialDao materialDao;

	@Autowired
	private MaterialEditDao materialEditDao;

	@Override
	public ResponseResult queryMaterialListByPassportId(int passportId, Integer width, Integer height, Integer currentPageIndex, Integer pageSize) {
		LOGGER.info("passportId = {}, width = {}, height = {}, currentPageIndex = {}, pageSize = {}", passportId, width, height, currentPageIndex, pageSize);
		
		ResponseResult responseResult = new ResponseResult();
		
		long totalCount = 0;	// 总素材数
		try {
			totalCount = this.pictureDao.selectMaterialTotalCountByPassportId(passportId);
		} catch (Exception e) {
			LOGGER.error("根据【通行证ID】查询【素材总记录数】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【通行证ID】查询【素材总记录数】 - 失败！");
			
			return responseResult;
		}
		
		if(0 == totalCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("未找到素材！");
			
			return responseResult;
		}
		
		if(null == currentPageIndex || 0 >= currentPageIndex) {
			currentPageIndex = 1;
		}
		if(null == pageSize || 0 >= pageSize) {
			pageSize = 10;
		}
		
		if(null == width) {
			width = -1;
		}
		if(null == height) {
			height = -1;
		}
		
		int offset = ( (currentPageIndex - 1) * pageSize ); // 设置分页的偏移量，即起始记录数
		int totalPageCount = (int) (0 < totalCount % pageSize ? totalCount / pageSize + 1 : totalCount / pageSize);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();	// 结果集
		
		if(currentPageIndex > totalPageCount - 1) {
			resultMap.put("isMore", false);
		} else {
			resultMap.put("isMore", true);
		}
		
		List<Map<String, Object>> pictureList = null;
		try {
			pictureList = this.pictureDao.selectPictureListByPassportId(passportId, offset, pageSize);
		} catch (Exception e) {
			LOGGER.error("根据【用户ID】查询【图片列表】 - 失败！", e);
		}

		if(CommonUtils.isEmpty(pictureList)) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("根据【用户ID】查询【素材列表】 - 成功。");
			
			return responseResult;
		}
		
		List<Map<String, String>> materialList = new ArrayList<Map<String, String>>();
		
		for(int index = 0; index < pictureList.size(); index++) {
			Map<String, Object> pictureMap = pictureList.get(index);
			
			if(CommonUtils.isEmpty(pictureMap)) {
				continue;
			}
			
			String originalImagePath = null;
			Map<String, String> materialMap = new HashMap<String, String>();
			
			if(null !=  pictureMap.get("id")) {
				materialMap.put("id", (String) pictureMap.get("id"));
			}
			if(null != pictureMap.get("original")) {
				originalImagePath = (String) pictureMap.get("original");
			}
			if(null != pictureMap.get("uploadTime")) {
				Date uploadTime =  (Date) pictureMap.get("uploadTime");
				materialMap.put("uploadDate", CommonUtils.dateFormat(uploadTime));
			}
			
			/*String originalImagePath = PropertiesUtils.getValue("material.image.original.path") + "2.jpg";
			if(OperationSystemInfo.isLinux() && StringUtils.isNotBlank(original)){
				originalImagePath = original;
			}*/
			
			String expandedName = ".jpg";	// 默认扩展名为 JPG
			if(StringUtils.isNotBlank(originalImagePath)) {
				int dotIndex = originalImagePath.lastIndexOf(".");
				
				if(0 < dotIndex){
					expandedName = originalImagePath.substring(dotIndex, originalImagePath.length());
					
					LOGGER.debug("expandedName = {}", expandedName);
				}
				
				int originalIndex = originalImagePath.indexOf("original");
				if(0 < originalIndex) {
					materialMap.put("original", PropertiesUtils.getValue("artup.mobile.url.perfix") + originalImagePath.substring(originalIndex, originalImagePath.length()));
				}
			}
			
			String newImagePath = PropertiesUtils.getValue("material.image.thumbnail.path") + CommonUtils.UUIDGenerator() + expandedName;
			if(-1 == width || 0 == width){
				ImageUtil.zoomImage(originalImagePath, newImagePath, null, height);
			} else if (-1 == height || 0 == height) {
				ImageUtil.zoomImage(originalImagePath, newImagePath, width, null);
			}
			
			if(StringUtils.isNotBlank(newImagePath)){
				if(OperationSystemInfo.isLinux()) {
					ChmodShell.updateFolderAuth(newImagePath);
				}
				
				int thumbnailIndex = newImagePath.indexOf("thumbnail");
				
				if(0 < thumbnailIndex) {
					materialMap.put("thumbnail", PropertiesUtils.getValue("artup.mobile.url.perfix") + newImagePath.substring(thumbnailIndex, newImagePath.length()));
				}
			}
			
			materialList.add(materialMap);
		}
		
		String usedSpaceKey = "usedSpace_" + passportId;
		LOGGER.debug("usedSpaceKey = {}", usedSpaceKey);
		String usedSpaceSize = jedis.get(usedSpaceKey);		// 已使用的空间大小
		
		/*String usedSpaceSize = null;
		List<String> usedSpaceSizeList = jedis.mget(usedSpaceKey);
		if(null != usedSpaceSizeList) {
			usedSpaceSize = usedSpaceSizeList.get(0);
		}*/
		LOGGER.debug("usedSpaceSize = {}", usedSpaceSize);
		
		if(StringUtils.isBlank(usedSpaceSize)) {
			resultMap.put("usedSpaceSize", 0);
		} else {
			resultMap.put("usedSpaceSize", usedSpaceSize);
		}
		resultMap.put("materialList", materialList);
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("根据【用户ID】查询【素材列表】 - 成功。");
		responseResult.setData(resultMap);
		
		return responseResult;
	}

	@Override
	public ResponseResult queryMaterialListByPassportId(int passportId, Integer currentPageIndex, Integer pageSize) {
		LOGGER.info("passportId = {}, currentPageIndex = {}, pageSize = {}", passportId, currentPageIndex, pageSize);
		
		ResponseResult responseResult = new ResponseResult();
		
		long totalCount = 0;	// 总素材数
		try {
			totalCount = this.pictureDao.selectMaterialTotalCountByPassportId(passportId);
		} catch (Exception e) {
			LOGGER.error("根据【通行证ID】查询【素材总记录数】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【通行证ID】查询【素材总记录数】 - 失败！");
			
			return responseResult;
		}
		
		if(0 == totalCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("未找到素材！");
			
			return responseResult;
		}
		
		if(null == currentPageIndex || 0 >= currentPageIndex) {
			currentPageIndex = 1;
		}
		if(null == pageSize || 0 >= pageSize) {
			pageSize = Integer.parseInt(PropertiesUtils.getValue("pagination.pageSize"));
		}
		
		int offset = ( (currentPageIndex - 1) * pageSize ); // 设置分页的偏移量，即起始记录数
		int totalPageCount = (int) (0 < totalCount % pageSize ? totalCount / pageSize + 1 : totalCount / pageSize);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();	// 结果集
		
		if(currentPageIndex > totalPageCount - 1) {
			resultMap.put("isMore", false);
		} else {
			resultMap.put("isMore", true);
		}
		
		List<Map<String, Object>> pictureList = null;
		try {
			pictureList = this.pictureDao.selectPictureListByPassportId(passportId, offset, pageSize);
		} catch (Exception e) {
			LOGGER.error("根据【用户ID】查询【图片列表】 - 失败！", e);
		}
		
		if(CommonUtils.isEmpty(pictureList)) {
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("未找到【素材列表】！");
			
			return responseResult;
		}
		
		List<Map<String, Object>> materialList = new ArrayList<Map<String, Object>>();
		
		for(int index = 0; index < pictureList.size(); index++) {
			Map<String, Object> pictureMap = pictureList.get(index);
			
			if(CommonUtils.isEmpty(pictureMap)) {
				continue;
			}
			
			Map<String, Object> materialMap = new HashMap<String, Object>();
			
			if(null !=  pictureMap.get("id")) {
				materialMap.put("id", (String) pictureMap.get("id"));
			}
			if(null !=  pictureMap.get("width")) {
				materialMap.put("originalImageWidth", pictureMap.get("width"));
			}
			if(null !=  pictureMap.get("height")) {
				materialMap.put("originalImageHeight", pictureMap.get("height"));
			}
			if(null !=  pictureMap.get("scale")) {
				materialMap.put("scale", pictureMap.get("scale"));
			}
			if(null != pictureMap.get("original")) {
				String originalImagePath = (String) pictureMap.get("original");	// 原图路径
				
				if(StringUtils.isNotBlank(originalImagePath)) {
					int originalIndex = originalImagePath.indexOf("original");
					if(0 < originalIndex) {
						materialMap.put("originalImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + originalImagePath.substring(originalIndex, originalImagePath.length()));
					}
				}
			}
			if(null != pictureMap.get("bigThumbnailImagePath")) {
				String bigThumbnailImagePath = (String) pictureMap.get("bigThumbnailImagePath");	// 大缩略图路径

				if(StringUtils.isNotBlank(bigThumbnailImagePath)) {
					int thumbnailIndex = bigThumbnailImagePath.indexOf("thumbnail");
					if(0 < thumbnailIndex) {
						materialMap.put("bigThumbnailImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + bigThumbnailImagePath.substring(thumbnailIndex, bigThumbnailImagePath.length()));
					}
				}
			}
			if(null != pictureMap.get("smallThumbnailImagePath")) {
				String smallThumbnailImagePath = (String) pictureMap.get("smallThumbnailImagePath");	// 小缩略图路径
				
				if(StringUtils.isNotBlank(smallThumbnailImagePath)) {
					int thumbnailIndex = smallThumbnailImagePath.indexOf("thumbnail");
					if(0 < thumbnailIndex) {
						materialMap.put("smallThumbnailImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + smallThumbnailImagePath.substring(thumbnailIndex, smallThumbnailImagePath.length()));
					}
				}
			}
			if(null != pictureMap.get("uploadTime")) {
				Date uploadTime =  (Date) pictureMap.get("uploadTime");
				materialMap.put("uploadDate", CommonUtils.dateFormat(uploadTime));
			}
			
			materialList.add(materialMap);
		}
		
		String usedSpaceKey = "usedSpace_" + passportId;
		LOGGER.debug("usedSpaceKey = {}", usedSpaceKey);
		String usedSpaceSize = jedis.get(usedSpaceKey);		// 已使用的空间大小
		
		/*String usedSpaceSize = null;
		List<String> usedSpaceSizeList = jedis.mget(usedSpaceKey);
		if(null != usedSpaceSizeList) {
			usedSpaceSize = usedSpaceSizeList.get(0);
		}*/
		LOGGER.debug("usedSpaceSize = {}", usedSpaceSize);
		
		if(StringUtils.isBlank(usedSpaceSize)) {
			resultMap.put("usedSpaceSize", 0);
		} else {
			resultMap.put("usedSpaceSize", usedSpaceSize);
		}
		resultMap.put("materialList", materialList);
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("根据【通行证ID】查询【素材列表】 - 成功。");
		responseResult.setData(resultMap);
		
		return responseResult;
	}

	@Override
	public ResponseResult saveMaterial(Material material) {
		LOGGER.info("material = {}", JSONObject.toJSONString(material));
		
		ResponseResult responseResult = new ResponseResult();
		
		return responseResult;
	}

	@Override
	public ResponseResult saveMaterial(MaterialTo materialTo) {
		LOGGER.info("materialTo = {}", JSONObject.toJSONString(materialTo));
		
		ResponseResult responseResult = new ResponseResult();
		
		if(null == materialTo) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("无参数！");
			
			return responseResult;
		}
		
		Material material = new Material();
		String id = CommonUtils.UUIDGenerator();
		material.setId(id);
		material.setPassportId(materialTo.getPassportId());
		material.setOriginalFileName(materialTo.getOriginalFileName());
		material.setSystemFileName(materialTo.getSystemFileName());
		material.setExpandedName(materialTo.getExpandedName());
		material.setOriginalSize(materialTo.getFileSize());
		if(StringUtils.isBlank(materialTo.getClientCode())) {
			material.setClientCode("ios");	// 默认 ios
		} else {
			material.setClientCode(materialTo.getClientCode());
		}
		
		Map<String, String> materialMap = new HashMap<String, String>();
		materialMap.put("id", material.getId());
		materialMap.put("passportId", String.valueOf(material.getPassportId()));
		
		String usedSpaceKey = "usedSpace_" + materialTo.getPassportId();
		
		String usedSpaceSize = jedis.get(usedSpaceKey);		// 已使用的空间大小
		
		/*String usedSpaceSize = null;
		List<String> usedSpaceSizeList = jedis.mget(usedSpaceKey);
		if(null != usedSpaceSizeList) {
			usedSpaceSize = usedSpaceSizeList.get(0);
		}*/
		LOGGER.debug("usedSpaceSize = {}", usedSpaceSize);
		
		BigDecimal addSpaceSize = BigDecimal.ZERO;		// 增加的空间大小
		
		if(StringUtils.isNotBlank(materialTo.getStoragePath())) {
			String orginalImagePath = materialTo.getStoragePath();	// 原图路径
			
			if(StringUtils.isNotBlank(materialTo.getClientCode())) {
				ImageUtil.processIosImageRotate(orginalImagePath);
			}
			
			addSpaceSize = addSpaceSize.add(BigDecimal.valueOf(materialTo.getFileSize()));	// 增加的原图大小
			
			material.setOrignalStoragePath(orginalImagePath);
			int originalImageWidth = ImageUtil.getImageWidth(orginalImagePath);	// 原图宽度
			int originalImageHeight = ImageUtil.getImageHeight(orginalImagePath);	// 原图高度
			material.setOriginalWidth(originalImageWidth);
			material.setOriginalHeight(originalImageHeight);
			
			String uploadPrefix = PropertiesUtils.getValue("material.image.thumbnail.path");
			
			String bigThumbnailImagePath = FolderUtils.getStoragePath(uploadPrefix, materialTo.getPassportId()) + CommonUtils.UUIDGenerator() + "_" + BIG_THUMBNAIL_SHORTEST_SIDE_LENGTH + "." + materialTo.getExpandedName();	// 大缩略图（绝对）路径
			String smallThumbnailImagePath = FolderUtils.getStoragePath(uploadPrefix, materialTo.getPassportId()) + CommonUtils.UUIDGenerator() + "_" + SMALL_THUMBNAIL_SHORTEST_SIDE_LENGTH + "." + materialTo.getExpandedName();	// 小缩略图（绝对）路径
			
			float zoomScale = 1;	// 缩放比---原图 ÷ 大缩略图
			
			if(originalImageWidth < originalImageHeight) {
				ImageUtil.zoomImage(orginalImagePath, bigThumbnailImagePath, BIG_THUMBNAIL_SHORTEST_SIDE_LENGTH, null);	// 按宽缩放
				ImageUtil.zoomImage(orginalImagePath, smallThumbnailImagePath, SMALL_THUMBNAIL_SHORTEST_SIDE_LENGTH, null);	// 按宽缩放

				zoomScale = (float) originalImageWidth / (float) BIG_THUMBNAIL_SHORTEST_SIDE_LENGTH;
			} else {
				ImageUtil.zoomImage(orginalImagePath, bigThumbnailImagePath, null, BIG_THUMBNAIL_SHORTEST_SIDE_LENGTH);	// 按高缩放
				ImageUtil.zoomImage(orginalImagePath, smallThumbnailImagePath, null, SMALL_THUMBNAIL_SHORTEST_SIDE_LENGTH);	// 按高缩放

				zoomScale = (float) originalImageHeight / (float) BIG_THUMBNAIL_SHORTEST_SIDE_LENGTH;
			}
			
			long thumbnailImageSize = FileHelper.getFileSize(bigThumbnailImagePath);
			
			if(OperationSystemInfo.isLinux()) {
				ChmodShell.updateFolderAuth(bigThumbnailImagePath);
				ChmodShell.updateFolderAuth(smallThumbnailImagePath);
			}
			
			material.setThumbnailStoragePath(bigThumbnailImagePath);
			material.setSmallThumbnailImagePath(smallThumbnailImagePath);
			material.setZoomScale(zoomScale);
			material.setThumbnailSize(thumbnailImageSize);
			
//			addSpaceSize = addSpaceSize.add(BigDecimal.valueOf(thumbnailImageSize));	// 增加的缩略图大小
			
			String originalImagePath = material.getOrignalStoragePath();	// 原图路径
			
			if(StringUtils.isNotBlank(originalImagePath)) {
				int originalIndex = originalImagePath.indexOf("original");
				if(0 < originalIndex) {
					materialMap.put("originalImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + originalImagePath.substring(originalIndex, originalImagePath.length()));
				}
			}
			if(StringUtils.isNotBlank(bigThumbnailImagePath)) {
				int thumbnailIndex = bigThumbnailImagePath.indexOf("thumbnail");
				if(0 < thumbnailIndex) {
					materialMap.put("bigThumbnailImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + bigThumbnailImagePath.substring(thumbnailIndex, bigThumbnailImagePath.length()));
				}
			}
			if(StringUtils.isNotBlank(smallThumbnailImagePath)) {
				int thumbnailIndex = smallThumbnailImagePath.indexOf("thumbnail");
				if(0 < thumbnailIndex) {
					materialMap.put("smallThumbnailImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + smallThumbnailImagePath.substring(thumbnailIndex, smallThumbnailImagePath.length()));
				}
			}
			if(StringUtils.isNotBlank(material.getUploadTime())) {
				materialMap.put("uploadTime", material.getUploadTime().substring(0, 16));
			}
		}
		
		try {
			this.materialDao.insertMaterial(material);
		} catch (Exception e) {
			LOGGER.error("添加【素材】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("添加【素材】 - 失败！");
			
			return responseResult;
		}
		
		LOGGER.debug("usedSpaceSize = {}", usedSpaceSize);
		
		if(StringUtils.isBlank(usedSpaceSize) || "null".equals(usedSpaceSize)) {
			jedis.set(usedSpaceKey, addSpaceSize.toString());
		} else {
			BigDecimal usedSpaceSize_ = new BigDecimal(usedSpaceSize);
			usedSpaceSize_ = usedSpaceSize_.add(addSpaceSize);

			jedis.set(usedSpaceKey, usedSpaceSize_.toString());
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("上传并保持【素材】 - 成功。");
		responseResult.setData(materialMap);
		
		return responseResult;
	}
	
	@Override
	public ResponseResult queryMaterialById(String id, Integer width, Integer height) {
		LOGGER.info("id = {}, width = {}, height = {}", id, width, height);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(StringUtils.isBlank(id)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【ID】不可为空！");
			
			return responseResult;
		}
		
		Material material = null;
		try {
			material = this.materialDao.selectMaterialById(id);
		} catch (Exception e) {
			LOGGER.error("根据【ID】查询【素材】 - 失败！", e);
		}

		if(null == material) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("根据【ID】查询【素材】 - 成功。");
			
			return responseResult;
		}
		
		Map<String, String> materialMap = new HashMap<String, String>();
		materialMap.put("id", material.getId());
		materialMap.put("passportId", String.valueOf(material.getPassportId()));
			
		String originalImagePath = null;
		if(StringUtils.isNotBlank(material.getOrignalStoragePath())) {
			originalImagePath = material.getOrignalStoragePath();
		}
		if(StringUtils.isNotBlank(material.getUploadTime())) {
			materialMap.put("uploadTime", material.getUploadTime().substring(0, 16));
		}
			
		String expandedName = ".jpg";	// 默认扩展名为 JPG
		if(StringUtils.isNotBlank(originalImagePath)) {
			int dotIndex = originalImagePath.lastIndexOf(".");
			
			if(0 < dotIndex){
				expandedName = originalImagePath.substring(dotIndex, originalImagePath.length());
				
				LOGGER.debug("expandedName = {}", expandedName);
			}
		}
			
		String thumbnailPrefix = PropertiesUtils.getValue("material.image.thumbnail.path");
		String newImagePath = FolderUtils.getStoragePath(thumbnailPrefix, material.getPassportId()) + CommonUtils.UUIDGenerator() + expandedName;
		LOGGER.info("newImagePath = " + newImagePath);
		
		if(null == width || -1 == width || 0 == width){
			ImageUtil.zoomImage(originalImagePath, newImagePath, null, height);
		} else if (null == height || -1 == height || 0 == height) {
			ImageUtil.zoomImage(originalImagePath, newImagePath, width, null);
		}
		
		if(StringUtils.isNotBlank(newImagePath)){
			if(OperationSystemInfo.isLinux()) {
				ChmodShell.updateFolderAuth(newImagePath);
			}
			
			int thumbnailIndex = newImagePath.indexOf("thumbnail");
			
			if(0 < thumbnailIndex) {
				materialMap.put("thumbnail", PropertiesUtils.getValue("artup.mobile.url.perfix") + newImagePath.substring(thumbnailIndex, newImagePath.length()));
			}
		}
			
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【素材】 - 成功。");
		responseResult.setData(materialMap);
		
		return responseResult;
	}
	
	@Override
	public ResponseResult queryMaterialById(String id) {
		LOGGER.info("id = {}", id);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(StringUtils.isBlank(id)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【ID】不可为空！");
			
			return responseResult;
		}
		
		Material material = null;
		try {
			material = this.materialDao.selectMaterialById(id);
		} catch (Exception e) {
			LOGGER.error("根据【ID】查询【素材】 - 失败！", e);
		}
		
		if(null == material) {
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("未找到【素材】！");
			
			return responseResult;
		}
		
		Map<String, Object> materialMap = new HashMap<String, Object>();
		materialMap.put("id", material.getId());
		materialMap.put("passportId", String.valueOf(material.getPassportId()));
		materialMap.put("originalImageWidth", material.getOriginalWidth());
		materialMap.put("originalImageHeight", material.getOriginalHeight());
		materialMap.put("scale", material.getZoomScale());
		
		if(StringUtils.isNotBlank(material.getOrignalStoragePath())) {
			String originalImagePath = material.getOrignalStoragePath();	// 原图路径
			
			if(StringUtils.isNotBlank(originalImagePath)) {
				int originalIndex = originalImagePath.indexOf("original");
				if(0 < originalIndex) {
					materialMap.put("originalImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + originalImagePath.substring(originalIndex, originalImagePath.length()));
				}
			}
		}
		if(StringUtils.isNotBlank(material.getThumbnailStoragePath())) {
			String bigThumbnailImagePath = material.getThumbnailStoragePath();	// 大缩略图路径

			if(StringUtils.isNotBlank(bigThumbnailImagePath)) {
				int thumbnailIndex = bigThumbnailImagePath.indexOf("thumbnail");
				if(0 < thumbnailIndex) {
					materialMap.put("bigThumbnailImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + bigThumbnailImagePath.substring(thumbnailIndex, bigThumbnailImagePath.length()));
				}
			}
		}
		if(StringUtils.isNotBlank(material.getSmallThumbnailImagePath())) {
			String smallThumbnailImagePath = material.getSmallThumbnailImagePath();	// 小缩略图路径
			
			if(StringUtils.isNotBlank(smallThumbnailImagePath)) {
				int thumbnailIndex = smallThumbnailImagePath.indexOf("thumbnail");
				if(0 < thumbnailIndex) {
					materialMap.put("smallThumbnailImagePath", PropertiesUtils.getValue("artup.mobile.url.perfix") + smallThumbnailImagePath.substring(thumbnailIndex, smallThumbnailImagePath.length()));
				}
			}
		}
		if(StringUtils.isNotBlank(material.getUploadTime())) {
			materialMap.put("uploadTime", material.getUploadTime().substring(0, 16));
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【素材】 - 成功。");
		responseResult.setData(materialMap);
		
		return responseResult;
	}
	
	@Override
	public ResponseResult batchDeleteMaterialById(String ids, int passportId) {
		LOGGER.info("ids = {}, passportId = {}", ids, passportId);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(StringUtils.isBlank(ids)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("无参数！");
			
			return responseResult;
		}
		
		int usedCount = 0;
		try {
			usedCount = this.materialEditDao.selectMaterialEditCountByMaterialIds(ids.split(","));
		} catch (SQLException e) {
			LOGGER.error("根据【素材IDs】查询【素材编辑数】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【素材IDs】查询【素材编辑数】 - 失败！");
			
			return responseResult;
		}
		
		if(0 < usedCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("含有已使用的素材，无法删除！");
			
			return responseResult;
		}
		
		List<Map<String, Object>> materialImagePathList = null;
		
		try {
			materialImagePathList = this.materialDao.batchSelectMaterialImagePathListByIds(ids.split(","));
		} catch (SQLException e) {
			LOGGER.error("根据【IDs】批量查询【素材图片路径列表】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【IDs】批量查询【素材图片路径列表】 - 失败！");
			
			return responseResult;
		}
		
		if(CommonUtils.isEmpty(materialImagePathList)) {
			responseResult.setStatus(Constants.ACTION_STATUS_RESULT_EMPTY);
			responseResult.setMessage("未找到素材！");
			
			return responseResult;
		}
		
//		BigDecimal totalSpaceSize = BigDecimal.valueOf(5368709120L);	// 总空间大小，默认为 5G = 1024 * 1024 * 1024 * 5
		String usedSpaceKey = "usedSpace_" + passportId;
		LOGGER.debug("usedSpaceKey = {}", usedSpaceKey);
		String usedSpaceSize = jedis.get(usedSpaceKey);		// 已使用的空间大小
		
		/*String usedSpaceSize = null;
		List<String> usedSpaceSizeList = jedis.mget(usedSpaceKey);
		if(null != usedSpaceSizeList) {
			usedSpaceSize = usedSpaceSizeList.get(0);
		}*/
		
		LOGGER.debug("删除素材前，usedSpaceSize = {}", usedSpaceSize);
		BigDecimal freeSpaceSize = BigDecimal.ZERO;		// 释放的空间大小
		
		try {
			this.materialDao.batchDeleteMaterialById(ids.split(","));
		} catch (Exception e) {
			LOGGER.error("根据【IDs】批量删除【素材】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【IDs】批量删除【素材】 - 失败！");
			
			return responseResult;
		}
		
		for(Map<String, Object> materialImagePath : materialImagePathList) {
			if(CommonUtils.isEmpty(materialImagePath)) {
				continue;
			}
			
			String orignalStoragePath = (String) materialImagePath.get("orignalStoragePath");
			String thumbnailStoragePath = (String) materialImagePath.get("thumbnailStoragePath");
			long originalSize = (long) materialImagePath.get("originalSize");
			long thumbnailSize = (long) materialImagePath.get("thumbnailSize");
			
			if(StringUtils.isNotBlank(orignalStoragePath)) {
				FileHelper.removeFile(orignalStoragePath);		// 删除原图
			}
			if(StringUtils.isNotBlank(thumbnailStoragePath)) {
				FileHelper.removeFile(thumbnailStoragePath);		// 删除缩略图
			}
			if(0 < originalSize) {
				freeSpaceSize = freeSpaceSize.add(BigDecimal.valueOf(originalSize));
			}
			if(0 < thumbnailSize) {
				freeSpaceSize = freeSpaceSize.add(BigDecimal.valueOf(thumbnailSize));
			}
		}
		
		if(StringUtils.isBlank(usedSpaceSize)){
			jedis.set(usedSpaceKey, "0");
			
			LOGGER.debug("删除素材后，usedSpaceSize = 0");
		} else {
			BigDecimal usedSpaceSize_ = new BigDecimal(usedSpaceSize);
			usedSpaceSize_ = usedSpaceSize_.subtract(freeSpaceSize);
			
			if(0 > usedSpaceSize_.doubleValue()) {
				jedis.set(usedSpaceKey, "0");

				LOGGER.debug("删除素材后，usedSpaceSize = 0");
			} else {
				jedis.set(usedSpaceKey, usedSpaceSize_.toString());

				LOGGER.debug("删除素材后，usedSpaceSize = {}", usedSpaceSize_);
			}
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("批量删除【素材】 - 成功。");
		
		return responseResult;
	}
	
	@Override
	public ResponseResult queryMaterialList(Material material) {
		LOGGER.info("material = {}", JSONObject.toJSONString(material));
		
		ResponseResult responseResult = new ResponseResult();
		
		if(null != material) {
			material.setBeginUploadTime(material.getBeginUploadTime() + " 00:00");
			material.setEndUploadTime(material.getEndUploadTime() + " 23:59");
		}
		
		long totalCount = 0;
		try {
			totalCount = this.materialDao.selectMaterialTotalCount(material);
		} catch (Exception e) {
			LOGGER.error("模糊查询【素材总记录数】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("模糊查询【素材总记录数】 - 失败！");
			
			return responseResult;
		}
		
		Map<String, Object> resultMap = new HashMap<String, Object>();	// 结果集
		responseResult.setData(resultMap);
		resultMap.put("totalCount", totalCount);

		if(0 == totalCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("未找到素材！");
			
			return responseResult;
		}
		
		if(null == material.getPageIndex() || 0 >= material.getPageIndex()) {
			material.setPageIndex(1);
		}
		if(null == material.getPageSize() || 0 >= material.getPageSize()) {
			material.setPageSize(Integer.valueOf(PropertiesUtils.getValue("pagination.pageSize")));
		}
		
		long offset = (material.getPageIndex() - 1) * material.getPageSize();	// 起始订单行号
		
		material.setOffset(offset);
		
		List<Material> materialList = null;
		try {
			materialList = this.materialDao.selectMaterialList(material);
		} catch (SQLException e) {
			LOGGER.error("模糊查询【素材列表】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("模糊查询【素材列表】 - 失败！");
			
			return responseResult;
		}

		resultMap.put("materialList", null);
		
		if(CommonUtils.isNotEmpty(materialList)) {
			List<MaterialVo> materialVoList = new ArrayList<MaterialVo>();
			resultMap.put("materialList", materialVoList);
			
			for(int index = 0; index < materialList.size(); index++) {
				Material material_ = materialList.get(index);
				
				if(null == material_) {
					continue;
				}
			
				MaterialVo materialVo = new MaterialVo();
				materialVo.setId(material_.getId());
				materialVo.setPassportId(material_.getPassportId());
				materialVo.setOriginalFileName(material_.getOriginalFileName());
				if(StringUtils.isNotBlank(material_.getUploadTime())) {
					materialVo.setUploadTime(material_.getUploadTime().substring(0, 16));
				}
				materialVo.setClientCode(material_.getClientCode());
				
				if(StringUtils.isNotBlank(material_.getThumbnailStoragePath())) {
					String materialThumbnailPath = material_.getThumbnailStoragePath();
					
					int materialThumbnailIndex = materialThumbnailPath.indexOf("edited");
					if(0 < materialThumbnailIndex) {
						materialVo.setThumbnailStoragePath(PropertiesUtils.getValue("artup.mobile.url.perfix") + materialThumbnailPath.substring(materialThumbnailIndex, materialThumbnailPath.length()));
					}
				}
				if(StringUtils.isNotBlank(material_.getSmallThumbnailImagePath())) {
					String smallThumbnailPath = material_.getSmallThumbnailImagePath();
					
					int smallThumbnailIndex = smallThumbnailPath.indexOf("edited");
					if(0 < smallThumbnailIndex) {
						materialVo.setSmallThumbnailImagePath(PropertiesUtils.getValue("artup.mobile.url.perfix") + smallThumbnailPath.substring(smallThumbnailIndex, smallThumbnailPath.length()));
					}
				}
				
				materialVoList.add(materialVo);
			}
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【素材列表】 - 成功。");
		
		return responseResult;
	}
}
